#include "func_update.h"
#include "usb_com.h"
#include "usb_device.h"
unsigned long updateFlag __attribute__((section(".ARM.__at_0x20004ff0")));
//unsigned char *updateFlag = (unsigned char *)0x20004ff0;
unsigned long Version __attribute__((section(".ARM.__at_0x800FC00"))) = VERSION;



void USB_Disconnected(void) {
    __HAL_RCC_USB_FORCE_RESET();
    HAL_Delay(200);
    __HAL_RCC_USB_RELEASE_RESET();
 
    GPIO_InitTypeDef GPIO_Initure;
    __HAL_RCC_GPIOA_CLK_ENABLE();
 
    GPIO_Initure.Pin = GPIO_PIN_11 | GPIO_PIN_12;
    GPIO_Initure.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_Initure.Pull = GPIO_PULLDOWN;
    GPIO_Initure.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOA, &GPIO_Initure);
 
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_11, GPIO_PIN_RESET);
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_12, GPIO_PIN_RESET);
    HAL_Delay(300);
}


void update_start(unsigned char cmd, unsigned char subCmd, unsigned char *data)
{
    usb_cmd(COMM_UPDATE, COMM_SUB_UPDATE_BEGIN, 0);
}


void update_version(unsigned char cmd, unsigned char subCmd, unsigned char *data)
{
    usb_cmd(COMM_UPDATE, COMM_SUB_UPDATE_VERSION,0);
}


void update_start_update(unsigned char cmd, unsigned char subCmd, void *param)
{
    unsigned char sendData[USB_PORT_SIZE] = {0};
    sendData[0] = 0xaa;
    sendData[1] = 0x55;
    sendData[2] = 7;
    sendData[3] = COMM_UPDATE;
    sendData[4] = COMM_SUB_UPDATE_BEGIN;
    sendData[5] = 0;
    sendData[6] = chksum(sendData, 6);
    usb_send(sendData, 7);
    while (USB_IDEL() == 0);
    updateFlag = 1;
    USB_Disconnected();
    // 关闭所有中断
    __set_FAULTMASK(1);
    // 复位
    NVIC_SystemReset();
}

void update_version_update(unsigned char cmd, unsigned char subCmd, void *param)
{
    unsigned char sendData[USB_PORT_SIZE] = {0};
    sendData[0] = 0xaa;
    sendData[1] = 0x55;
    sendData[2] = 11;
    sendData[3] = COMM_UPDATE;
    sendData[4] = COMM_SUB_UPDATE_VERSION;
    sendData[5] = 0;
    sendData[6] = VERSION>>24&0xff;
    sendData[7] = VERSION>>16&0xff;
    sendData[8] = VERSION>>8&0xff;
    sendData[9] = VERSION&0xff;
    sendData[10] = chksum(sendData, 10);
    usb_send(sendData, 11);
}
